<?php

/**
 * Step 1: Require the Slim Framework
 *
 * If you are not using Composer, you need to require the
 * Slim Framework and register its PSR-0 autoloader.
 *
 * If you are using Composer, you can skip this step.
 */
require 'Slim/Slim.php';
require 'SD/utils.php';
require 'SD/authentication.php';

\Slim\Slim::registerAutoloader();

/**
 * Step 2: Instantiate a Slim application
 *
 * This example instantiates a Slim application using
 * its default settings. However, you will usually configure
 * your Slim application now by passing an associative array
 * of setting names and values into the application constructor.
 */
$app = new \Slim\Slim();

/**
 * Step 3: Define the Slim application routes
 *
 * Here we define several Slim application routes that respond
 * to appropriate HTTP request methods. In this example, the second
 * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete`
 * is an anonymous function.
 */
// GET route
$app->post(
        '/',
        function () {
            $template = <<<EOT
<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8"/>
            <title>Simply Decide API Module</title>
            <style>
                html,body,div,span,object,iframe,
                h1,h2,h3,h4,h5,h6,p,blockquote,pre,
                abbr,address,cite,code,
                del,dfn,em,img,ins,kbd,q,samp,
                small,strong,sub,sup,var,
                b,i,
                dl,dt,dd,ol,ul,li,
                fieldset,form,label,legend,
                table,caption,tbody,tfoot,thead,tr,th,td,
                article,aside,canvas,details,figcaption,figure,
                footer,header,hgroup,menu,nav,section,summary,
                time,mark,audio,video{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent;}
                body{line-height:1;}
                article,aside,details,figcaption,figure,
                footer,header,hgroup,menu,nav,section{display:block;}
                nav ul{list-style:none;}
                blockquote,q{quotes:none;}
                blockquote:before,blockquote:after,
                q:before,q:after{content:'';content:none;}
                a{margin:0;padding:0;font-size:100%;vertical-align:baseline;background:transparent;}
                ins{background-color:#ff9;color:#000;text-decoration:none;}
                mark{background-color:#ff9;color:#000;font-style:italic;font-weight:bold;}
                del{text-decoration:line-through;}
                abbr[title],dfn[title]{border-bottom:1px dotted;cursor:help;}
                table{border-collapse:collapse;border-spacing:0;}
                hr{display:block;height:1px;border:0;border-top:1px solid #cccccc;margin:1em 0;padding:0;}
                input,select{vertical-align:middle;}
                html{ background: #EDEDED; height: 100%; }
                body{background:#FFF;margin:0 auto;min-height:100%;padding:0 30px;width:440px;color:#666;font:14px/23px Arial,Verdana,sans-serif;}
                h1,h2,h3,p,ul,ol,form,section{margin:0 0 20px 0;}
                h1{color:#333;font-size:20px;}
                h2,h3{color:#333;font-size:14px;}
                h3{margin:0;font-size:12px;font-weight:bold;}
                ul,ol{list-style-position:inside;color:#999;}
                ul{list-style-type:square;}
                code,kbd{background:#EEE;border:1px solid #DDD;border:1px solid #DDD;border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px;padding:0 4px;color:#666;font-size:12px;}
                pre{background:#EEE;border:1px solid #DDD;border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px;padding:5px 10px;color:#666;font-size:12px;}
                pre code{background:transparent;border:none;padding:0;}
                a{color:#70a23e;}
                header{padding: 30px 0;text-align:center;}
            </style>
        </head>
        <body>
            <header>
                <a href="http://www.slimframework.com"><img src="" alt="Slim"/></a>
				<br>
				<a href="http://www.simplydecide.com">SimplyDecide</a>
            </header>
            <h1>Welcome to Slim!</h1>
            <p>
                Congratulations! Your Slim application is running. If this is
                your first time using Slim, start with this <a href="http://www.slimframework.com/learn" target="_blank">"Hello World" Tutorial</a>.
            </p>
            <section>
                <h2>Get Started</h2>
                <ol>
                    <li>The application code is in <code>index.php</code></li>
                    <li>Read the <a href="http://docs.slimframework.com/" target="_blank">online documentation</a></li>
                    <li>Follow <a href="http://www.twitter.com/slimphp" target="_blank">@slimphp</a> on Twitter</li>
                </ol>
            </section>
            <section>
                <h2>Slim Framework Community</h2>

                <h3>Support Forum and Knowledge Base</h3>
                <p>
                    Visit the <a href="http://help.slimframework.com" target="_blank">Slim support forum and knowledge base</a>
                    to read announcements, chat with fellow Slim users, ask questions, help others, or show off your cool
                    Slim Framework apps.
                </p>

                <h3>Twitter</h3>
                <p>
                    Follow <a href="http://www.twitter.com/slimphp" target="_blank">@slimphp</a> on Twitter to receive the very latest news
                    and updates about the framework.
                </p>
            </section>
            <section style="padding-bottom: 20px">
                <h2>Slim Framework Extras</h2>
                <p>
                    Custom View classes for Smarty, Twig, Mustache, and other template
                    frameworks are available online in a separate repository.
                </p>
                <p><a href="https://github.com/codeguy/Slim-Extras" target="_blank">Browse the Extras Repository</a></p>
            </section>
        </body>
    </html>
EOT;
            echo $template;
        }
);

$app->get('/hello', function () {
            echo "Hello, Dilip";
        });

$app->get('/hello/:name', function ($name) {
            echo "Hello, $name";
        });

$app->get('/', function () {
	$list = 'country';
            if ($list == 'country') {
                $link = getDbLink();
                $query = "select `country_id`, `name` from `oc_country`";
                $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
                $records = array();
                if (mysql_num_rows($result)) {
                    while ($record = mysql_fetch_assoc($result)) {
                        $records[] = array('results' => $record);
                    }
                }
                header('Content-type: application/json');
                echo json_encode(array('records' => $records));
                closeDbLink($link);
            } else if ($list == 'region') {
                $link = getDbLink();
                $query = 'select * from `oc_zone`';
                $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
                $records = array();
                if (mysql_num_rows($result)) {
                    while ($record = mysql_fetch_assoc($result)) {
                        //var_dump(array('record'=>$record));
                        $records[] = array('record' => $record);
                    }
                } else {
                    $record = array(
                        "zone_id" => 0,
                        "name" => "--",
                    );
                    $records[] = array('record' => $record);
                }
                header('Content-type: application/json');
                //var_dump(json_encode(array('results'=>$records)));
                //echo json_last_error();
                echo json_encode(array('results' => $records));
                closeDbLink($link);
            } else {
                echo 'unknown header';
            }
        });

$app->get('/logout', function () {
            session_start();
            session_destroy();
        });

$app->get(
        '/authenticate/user',
        function () {
            //echo 'Boom';
            session_start();
            if (!empty($_SESSION['user_id'])) {
                echo $_SESSION['user_id'];
            } else {
                echo 'No VALID session';
            }
        }
);

// POST route
$app->post(
        '/authenticate',
        function () {
//            console.log(here);
            $username = isset($_POST['usr']) ? $_POST['usr'] : 0;
            $password = isset($_POST['pwd']) ? $_POST['pwd'] : 0;
//            echo $username;
            login($username, $password);
        }
);

$app->post('/signup', function() {
            $link = getDbLink();
            $login = isset($_POST['login']) ? $_POST['login'] : "";
            $query = "select `customer_id` from `oc_customer` where`email`='" . $login . "'";
            $result = mysql_query($query, $link) or die('Errant query:  ' . $query);
            if (mysql_num_rows($result)) {
                echo json_encode(array('result' => 'failure', 'message' => 'already existing email id'));
                break;
            }

            $password = isset($_POST['password']) ? $_POST['password'] : "";
            $firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
            $lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
            $gender = isset($_POST['lastname']) ? $_POST['lastname'] : "";
            $countrycode = isset($_POST['countrycode']) ? $_POST['countrycode'] : 0;
            $regioncode = isset($_POST['regioncode']) ? $_POST['regioncode'] : 0;

            try {
                begin($link);
                $salt = substr(md5(uniqid(rand(), true)), 0, 9);
                $encodedpassword = sha1($salt . sha1($salt . sha1($password)));
                $query1 = "insert into `oc_customer` (`firstname`, `lastname`, `gender`,`email`,`password`, `salt`,`date_added`) values ('" . $firstname . "', '" . $lastname . "', '" . $gender . "','" . $login . "','" . $encodedpassword . "','" . $salt . "',now());";
                $result = mysql_query($query1, $link);
                $query3 = "SELECT `customer_id` FROM  `oc_customer` WHERE `email`='" . $login . "'";
                $result = mysql_query($query3, $link);
                $resultarray = mysql_fetch_assoc($result);
                $assignedId = $resultarray['customer_id'];
                $query2 = "insert into `oc_address` (`customer_id`,`firstname`, `lastname`,`country_id`,`zone_id`) values ('" . $assignedId . "','" . $firstname . "', '" . $lastname . "', " . intval($countrycode) . "," . intval($regioncode) . ")";
                //echo $query2;
                $result = mysql_query($query2, $link);
                commit($link);
                echo json_encode(array('result' => 'success', "id" => $assignedId));
            } catch (Exception $e) {
                rollback($link);
                echo json_encode(array('result' => 'failure'));
            }
            closeDbLink($link);
        });



// PUT route
$app->put(
        '/put',
        function () {
            echo 'This is a PUT route';
        }
);

// PATCH route
$app->patch('/patch', function () {
            echo 'This is a PATCH route';
        });

// DELETE route
$app->delete(
        '/delete',
        function () {
            echo 'This is a DELETE route';
        }
);

/**
 * Step 4: Run the Slim application
 *
 * This method should be called last. This executes the Slim application
 * and returns the HTTP response to the HTTP client.
 */
$app->run();
